/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.action;

import java.util.ArrayList;
import java.util.HashMap;

import com.bluestone.BaseAction;
import com.bluestone.context.ActionContext;
import com.bluestone.context.IContext;
import com.bluestone.scripts.ActionScript;
import com.bluestone.scripts.Function;
import com.bluestone.util.Util;

/**
 * CallFuntionAction can execute a function.
 * @author <a href="mailto:bluesotne.master@gmail.com">daniel.q</a>
 */
public class CallFunctionAction extends BaseAction {
	public CallFunctionAction(ActionScript action){
		super(action);
	}


	/**
	 * This action can execute a function.
	 * @return false if the target is not exsit or if the function execute failure.
	 */
	public boolean execute(IContext context){
		ActionContext actionContext = (ActionContext)context;
		String target = action.getPara("target");
		if(target==null || target.length()==0){
			Util.error("action target is null or empty "+target);
			return false;
		}
		Function function = actionContext.getProjectContext().getProject().searchFunction(target);
		if(function == null){
			Util.error(Util.ERROR1+target);
			return false;
		}
		
		HashMap paras = new HashMap();		
		String value = action.getPara("value");
		if(value!=null){
		String [] tokens = value.split("[,=]");
		for(int i=0; i< tokens.length ; i=i+2){
			String k = tokens[i];
			String v = tokens[i+1];
			if(v.startsWith("@")){
				v = Util.getString(v);
			}
			paras.put(k,v);
		}
		}

		ArrayList actions = function.compile(paras);
				
		for(int i=0; i< actions.size(); i++){
			ActionScript action = (ActionScript)actions.get(i);
			BaseAction baseAction = ActionFactory.createAction(action);
			if(!baseAction.isValid(context)){
				continue;
			}			
			baseAction.setParent(this.getParent());
			boolean flag = baseAction.execute(context);
			Util.info("run " + baseAction.toString() + "-->" + flag);			
			if(!flag){
				Util.warn("run " + baseAction.toString() + "-->" + flag);				
				return false;
			}
		}
		String delay = action.getPara("delay");
		if (delay != null && delay.length() > 0) {
			robot.delay(Util.getDelayTime(Integer.parseInt(delay)));
		} else {
			robot.delay(Util.getDelayTime(Util.CALLFUNCTIONDELAY));
		}		
		return true;
	}

}
